package com.hzh.cusviewdemo.Activity;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hzh.cusviewdemo.Adapter.SongMenuMusicAdapter;
import com.hzh.cusviewdemo.Base.BaseActivity;
import com.hzh.cusviewdemo.Bean.MusicInfoData;
import com.hzh.cusviewdemo.Bean.MyMusicData;
import com.hzh.cusviewdemo.Bean.MySongMenu;
import com.hzh.cusviewdemo.Music.Constant;
import com.hzh.cusviewdemo.Music.MusicPlayService;
import com.hzh.cusviewdemo.Music.MyMusicUtil;
import com.hzh.cusviewdemo.Presenter.MusicPresenter;
import com.hzh.cusviewdemo.R;
import com.hzh.cusviewdemo.Ui.classicFoot.footer.ClassicsFooter;
import com.hzh.cusviewdemo.Util.Config;
import com.hzh.cusviewdemo.Util.DialogUtils;
import com.hzh.cusviewdemo.Util.SugarUtils;
import com.hzh.cusviewdemo.Util.ThreadPoolManager;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.List;

/**
 * 查看歌单
 */
public class LookSongMenuActivity extends BaseActivity implements View.OnClickListener, MusicPresenter {

    private ImageView amm_back;
    private TextView amm_menu_name;
    private LinearLayout amm_linear_listen_all;
    private TextView amm_tv_all_count;
    private SmartRefreshLayout amm_smart;
    private RecyclerView amm_list_music;

    // 分页列表控件
    private SongMenuMusicAdapter menuMusicAdapter; // 歌单歌曲适配器

    // 传递过来的歌单名
    private String menuName = "";

    @Override
    public int getLayout() {
        return R.layout.activity_menu_music;
    }

    @Override
    public void initView() {
        amm_back = findViewById(R.id.amm_back);
        amm_menu_name = findViewById(R.id.amm_menu_name);
        amm_linear_listen_all = findViewById(R.id.amm_linear_listen_all);
        amm_tv_all_count = findViewById(R.id.amm_tv_all_count);
        amm_smart = findViewById(R.id.amm_smart);
        amm_list_music = findViewById(R.id.amm_list_music);

        amm_smart.setEnableRefresh(false);
        amm_smart.setRefreshFooter(new ClassicsFooter(this));
        amm_smart.setOnLoadMoreListener(refreshLayout -> {
            if (menuMusicAdapter != null) {
                menuMusicAdapter.loadMore();
                amm_smart.finishLoadMore(500);//传入false表示加载失败
            } else {
                amm_smart.finishLoadMore();
            }
        });

        amm_back.setOnClickListener(this);
        amm_linear_listen_all.setOnClickListener(this);
    }

    @Override
    public void initData() {
        // 加载歌单歌曲
        menuName = getIntent().getStringExtra("TAG_MENU_NAME");
        amm_menu_name.setText(menuName);
        getMenuMusicList(menuName);
    }

    /**
     * 加载历史记录
     */
    private void getMenuMusicList(String menuName) {
        ThreadPoolManager.getInstance().execute(() -> {
            List<MyMusicData> musicDataList = SugarUtils.findMusicDataByMenu(menuName);
            runOnUiThread(() -> {
                amm_tv_all_count.setText("播放全部（" + musicDataList.size() + "）");
                if (musicDataList.size() > 0) {
                    menuMusicAdapter = new SongMenuMusicAdapter(LookSongMenuActivity.this, musicDataList);
                    menuMusicAdapter.setOnListenMusicListener(new SongMenuMusicAdapter.OnListenMusicListener() {
                        @Override
                        public void onListenMusic(MyMusicData musicData, int pos) {
                            Log.e(Config.TAG, "播放歌曲SID -> " + musicData.getSid());
                            listenMusic(LookSongMenuActivity.this, musicData.getSid(), new MusicPresenter.OnListenMusicListener() {
                                @Override
                                public void onListenSuccess(MusicInfoData data) {
                                    MyMusicUtil.setShared(Constant.KEY_NAME, data.getSongname());
                                    MyMusicUtil.setShared(Constant.KEY_SONGER, data.getSonger());
                                    MyMusicUtil.setShared(Constant.KEY_PIC, data.getSongpic());
                                    String songTitle = data.getSongname() + " - " + data.getSonger();

                                    // 获取到musicUrl
                                    // 先暂停
                                    Intent stopIntent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                                    stopIntent.putExtra(Constant.COMMAND, Constant.COMMAND_STOP);
                                    sendBroadcast(stopIntent);

                                    MyMusicUtil.setShared(Constant.KEY_PATH, data.getSongurl());
                                    MyMusicUtil.setShared(Constant.KEY_ID, String.valueOf(data.getSid()));
                                    MyMusicUtil.setShared(Constant.KEY_TITLE, songTitle);

                                    Log.e(Config.TAG, "MA:保存本地播放列表：" + data.getSongname());

                                    MyMusicData musicDataByRid = SugarUtils.findMusicDataByRidOrSid(data.getSid());
                                    MyMusicData nextData = new MyMusicData();
                                    if (musicDataByRid == null) {
                                        // 添加到本地播放列表
                                        nextData.setRid(String.valueOf(data.getSid()));
                                        nextData.setSid(String.valueOf(data.getSid()));
                                        nextData.setName(data.getSongname());
                                        nextData.setSonger(data.getSonger());
                                        nextData.setTitle(songTitle);
                                        nextData.setPic(data.getSongpic());
                                        nextData.setUrl(data.getSongotherurl());
                                        nextData.setLrc(data.getSonglrc());
                                        nextData.setType("0"); // 顺序播放
                                        nextData.setMenu("全部歌曲");
                                        nextData.setCreateTime(TimeUtils.getNowString());
                                        SugarUtils.addMusicData(nextData);

                                        // 更新歌单
                                        MySongMenu songMenu = SugarUtils.getSongMenuByName("全部歌曲");
                                        if (songMenu != null) {
                                            songMenu.setNum(songMenu.getNum() + 1);
                                            songMenu.setPic(data.getSongpic());
                                            songMenu.setUpdateTime(TimeUtils.getNowString());
                                            songMenu.save();
                                        }
                                    } else {
                                        musicDataByRid.setUrl(data.getSongotherurl());
                                        musicDataByRid.setLrc(data.getSonglrc());
                                        musicDataByRid.save();
                                    }

                                    // 设置当前播放的歌单
                                    MyMusicUtil.setShared(Constant.KEY_NOW_PLAY_MENU, musicData.getMenu());

                                    // 通知MusicActivity处理STATUS_CLICK_SEARCH_RESULT_PLAY状态广播
                                    Intent musicIntent = new Intent(MusicActivity.ACTION_UPDATE_UI_MUSIC);
                                    musicIntent.putExtra(Constant.STATUS, Constant.STATUS_CLICK_SEARCH_RESULT_PLAY);
                                    sendBroadcast(musicIntent);

                                    // 通知播放音乐
                                    Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
                                    intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
                                    intent.putExtra(Constant.KEY_PATH, data.getSongotherurl());
                                    intent.putExtra(Constant.KEY_ID, musicDataByRid == null ? nextData.getSid() : musicDataByRid.getSid());
                                    intent.putExtra(Constant.KEY_TITLE, songTitle);
                                    sendBroadcast(intent);
                                }

                                @Override
                                public void onListenFail(String msg) {
                                    ToastUtils.showShort(msg);
                                }
                            });
                        }

                        @Override
                        public void onLongClickMusic(MyMusicData musicData, int pos) {
                            // delete music
                            DialogUtils.showYesOrNoTipDialog("删除歌曲?", "确定删除 " + musicData.getName() + "-" + musicData.getSonger() + " 这首歌曲吗?\n删除后不可撤销~", "取消", "删除", true, new DialogUtils.YesOrNoDismissCallBack() {
                                @Override
                                public void onDone(CustomDialog dialog) {
                                    // delete music
                                    musicData.delete();
                                    // 刷新对应歌单的数量
                                    MySongMenu songMenu = SugarUtils.getSongMenuByName(menuName);
                                    if (songMenu != null) {
                                        songMenu.setNum(songMenu.getNum() - 1);
                                        List<MyMusicData> musicDataByMenu = SugarUtils.findMusicDataByMenu(menuName);
                                        MyMusicData lastMusicData = musicDataByMenu.get(musicDataByMenu.size() - 1);
                                        songMenu.setPic(lastMusicData.getPic());
                                        songMenu.setUpdateTime(TimeUtils.getNowString());
                                        songMenu.save();
                                    }
                                    // 更新歌单
                                    runOnUiThread(() -> {
                                        // 刷新列表
                                        getMenuMusicList(menuName);
                                        // TODO 切换歌曲
                                    });
                                    dialog.dismiss();
                                }

                                @Override
                                public void onCancel(CustomDialog dialog) {
                                    dialog.dismiss();
                                }
                            });
                        }
                    });
                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
                    amm_list_music.setLayoutManager(linearLayoutManager);
                    amm_list_music.setAdapter(menuMusicAdapter);
                } else {
                    DialogUtils.showSuccessToast("歌单下还没有数据~");
                }
            });
        });
    }

    @Override
    public void onClick(View view) {
        if (view == amm_back) {
            finish();
        } else if (view == amm_linear_listen_all) {
            // 播放全部
            playAllMusic();
        }
    }

    /**
     * 播放全部歌曲
     */
    private void playAllMusic() {
        // 加载一下
        WaitDialog.show("");
        // 将当前的播放类型记录
        MyMusicUtil.setShared(Constant.KEY_NOW_PLAY_MENU, menuName);
        // 发送播放的指令
        String nowMusicMenu = MyMusicUtil.getStringShared(Constant.KEY_NOW_PLAY_MENU);
        List<MyMusicData> musicData = SugarUtils.findMusicDataByMenu(nowMusicMenu);
        if (musicData.size() == 0) {
            DialogUtils.showErrorToast("无法播放，没有歌曲~");
            WaitDialog.dismiss();
            return;
        }
        // 拿到第一首歌曲
        MyMusicData firstPlayMusic = musicData.get(0);
        if (firstPlayMusic == null) {
            WaitDialog.dismiss();
            return;
        }
        MyMusicData musicDataByRid = SugarUtils.findMusicDataByRidOrSid(firstPlayMusic.getSid());
        String path = musicDataByRid.getUrl();
        Log.d(Config.TAG, "LSM:" + "准备播放全部歌曲 第一首名称 =" + musicDataByRid.getName() + " 第一首歌曲 path =" + path);
        //发送播放请求
        Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
        MyMusicUtil.setShared(Constant.KEY_ID, musicDataByRid.getSid());
        MyMusicUtil.setShared(Constant.KEY_NAME, musicDataByRid.getName());
        MyMusicUtil.setShared(Constant.KEY_SONGER, musicDataByRid.getSonger());
        MyMusicUtil.setShared(Constant.KEY_PIC, musicDataByRid.getPic());
        intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
        intent.putExtra(Constant.KEY_PATH, path);
        intent.putExtra(Constant.KEY_ID, firstPlayMusic.getSid());
        intent.putExtra(Constant.KEY_TITLE, musicDataByRid.getTitle());
        sendBroadcast(intent);
        WaitDialog.dismiss();
    }

}